import { statusName } from "../constants";
import BaseNode from "./BaseNode";
import BehaviorTree from "./BehaviorTree";
import Blackboard from "./Blackboard";
class Entry {
  name: string
  indent: number
  constructor(name: string, preEntry: Entry | undefined, public isPush: boolean, public status: string = '') {
    this.name = isPush ? '╚═ ' + name + ' ═╗' : '╔═ ' + name + ' ═╝'
    if (preEntry) {
      this.indent = preEntry.isPush ? (isPush ? preEntry.length() : preEntry.indent) : (isPush ? preEntry.indent : preEntry.indent - this.name.length + 1)
    } else {
      this.indent = 0
    }
  }

  createSpace() {
    return ' '.repeat(this.indent)
  }

  finish() {
    return '╔' + (this.isPush ? '~'.repeat(this.length() - 1) : '═'.repeat(this.indent - 1)) + '╝'
  }

  length() {
    return this.indent + this.name.length - 1
  }

}

const space = '───────────────────────────────────────────────────────────────────────────'

export default class Tick {

  readonly tree: BehaviorTree
  readonly blackboard: Blackboard

  debug = true
  treeNodes: Entry[] = []

  constructor(tree: BehaviorTree) {
    this.tree = tree;
    this.blackboard = tree.blackboard;
  }

  setDebug(debug: boolean) {
    this.debug = debug
    return this
  }

  enterNode(node: BaseNode) {
    if (this.debug) {
      this.treeNodes.push(new Entry(node.name, this.treeNodes[this.treeNodes.length - 1], true))
    }
  }

  openNode(node: BaseNode) {
  }

  tickNode(node: BaseNode) {
  }

  closeNode(node: BaseNode) {
  }

  exitNode(node: BaseNode, status: number) {
    if (this.debug) {
      this.treeNodes.push(new Entry(node.name, this.treeNodes[this.treeNodes.length - 1], false, statusName(status)))
    }
  }

  execute(target: any, ...args: any[]): number {
    const startTime = new Date()
    var state = this.tree.root.execute(this, target, ...args);
    // 打印执行行为树
    if (this.debug) {
      console.log(`┌─ ${startTime.getUTCHours()}:${startTime.getUTCMinutes()}:${startTime.getUTCSeconds()}:${startTime.getMilliseconds()} ───────────────────────────────────────────────────────`)
      this.treeNodes.forEach((value) => {
        console.log('├' + value.createSpace() + value.name + value.status)
      })
      const last = this.treeNodes[this.treeNodes.length - 1]
      if (last.indent > 0) {
        console.log('├' + last.finish())
      }
      console.log(`└─────────────────────────────────────────────────────────────────────┘`)
    }
    return state;
  }
};
